<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\SearchLog;
use app\common\library\Withdraw as WithdrawService;

/**
 * 老师接口
 */
class Teacher extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        // 检查是否是老师
        if (!$this->auth->is_teacher) {
            $this->error('非老师用户无权访问');
        }
    }

    /**
     * 我的客户订单
     * 
     * @ApiTitle    (我的客户订单列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="status", type="integer", required=false, description="状态:0=待支付,1=已支付,2=已完成,3=已取消", default="all")
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "订单ID",
            "order_no": "订单编号",
            "service_name": "服务名称",
            "user_nickname": "客户昵称",
            "user_avatar": "客户头像",
            "amount": "订单金额",
            "status": "订单状态:0=待支付,1=已支付,2=已完成,3=已取消",
            "pay_time": "支付时间",
            "complete_time": "完成时间",
            "createtime": "创建时间"
          }]
        }
      })
     */
    public function orders()
    {
        $status = $this->request->get('status',0);
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        $keyword = $this->request->get('keyword', '');
        $user_id = $this->request->get('user_id', 0);
        $query = Db::name('service_order')->alias('o')
            ->join('service s', 's.id = o.service_id')
            ->join('user u', 'u.id = o.user_id')
            ->where('o.teacher_id', $this->auth->id)
            ->field([
                'o.*',
                's.name as service_name',
                's.cover_image as service_cover',  // 新增封面图字段
                'u.nickname as user_nickname',
                'u.avatar as user_avatar'
            ])
            ->order('o.id DESC');
            
        if($status !== 'all'){
            $query->where('o.status', intval($status));
        }
        if($user_id){
            $query->where('o.user_id', $user_id);
        }
        // 添加关键词搜索
        if($keyword){
            $query->where(function($query) use ($keyword) {
                $query->where('s.name', 'like', "%{$keyword}%")
                    ->whereOr('u.nickname', 'like', "%{$keyword}%")
                    ->whereOr('o.order_no', 'like', "%{$keyword}%");
            });
            // 记录搜索历史
            SearchLog::record($this->auth->id, $keyword, 'teacher_service_order');
        }
        
        $list = $query->page($page, $pageSize)->select();
        $total = Db::name('service_order')->alias('o')
        ->join('service s', 's.id = o.service_id')
        ->join('user u', 'u.id = o.user_id')
        ->where('o.teacher_id', $this->auth->id)
        ->where(function($query) use ($status, $user_id,$keyword) {
            if($status !== 'all'){
                $query->where('o.status', intval($status));
            }
            if($user_id){
                $query->where('o.user_id', $user_id);
            }
            if($keyword){
                $query->where(function($query) use ($keyword) {
                    $query->where('s.name', 'like', "%{$keyword}%")
                        ->whereOr('u.nickname', 'like', "%{$keyword}%")
                        ->whereOr('o.order_no', 'like', "%{$keyword}%");
                });
            }
        })
        ->count();
        // 格式化时间
        foreach($list as &$item){
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
            $item['pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : null;
            $item['complete_time'] = $item['complete_time'] ? date('Y-m-d H:i:s', $item['complete_time']) : null;
            $item['service_cover'] = cdnurl($item['service_cover']);  // 处理封面图完整路径
        }
        
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }

    /**
     * 余额变动明细
     * 
     * @ApiTitle    (余额变动明细)
     * @ApiMethod   (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "记录ID",
            "money": "变动金额",
            "before": "变动前余额",
            "after": "变动后余额",
            "memo": "变动说明",
            "type": "变动类型",
            "service_order_id": "关联服务订单ID",
            "createtime": "创建时间"
          }]
        }
      })
     */
    public function moneyLog()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        
        $query = Db::name('user_money_log')
            ->where('user_id', $this->auth->id)
            ->order('id DESC');
        
        $total = Db::name('user_money_log')
        ->where('user_id', $this->auth->id)->count();
        $list = $query->page($page, $pageSize)->select();
        
        // 格式化时间
        foreach($list as &$item){
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
        }
        
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }

    /**
     * 我的服务项目列表
     * 
     * @ApiTitle    (我的服务项目列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量",
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "关联ID",
            "service_id": "服务ID",
            "service_name": "服务名称",
            "icon": "图标",
            "cover_image": "封面图",
            "price": "价格",
            "description": "描述",
            "status": "状态:normal=上架,hidden=下架",
            "is_recommend": "是否推荐",
            "is_hot": "是否热门",
            "createtime": "创建时间"
          }]
        }
      })
     */
    public function services()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        
        $query = Db::name('service_teacher')->alias('st')
            ->join('service s', 's.id = st.service_id')
            ->where('st.teacher_id', $this->auth->id)
            ->field([
                'st.*',
                's.name as service_name',
                's.icon',
                's.cover_image',
                'st.price',
                's.description'
            ])
            ->order('st.weigh DESC, st.id DESC');
        
        
        $list = $query->page($page, $pageSize)->select();
        $total = Db::name('service_teacher')->alias('st')
        ->join('service s', 's.id = st.service_id')
        ->where('st.teacher_id', $this->auth->id)
        ->field([
            'st.*',
            's.name as service_name',
            's.icon',
            's.cover_image',
            'st.price',
            's.description'
        ])
        ->count();
        // 格式化时间
        foreach($list as &$item){
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
        }
        
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }
    
    /**
     * 设置服务状态
     * 
     * @ApiTitle    (设置服务上下架)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="服务老师关联ID")
     * @ApiParams   (name="status", type="string", required=true, description="状态:normal=上架,hidden=下架")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": null
      })
     */
    public function setServiceStatus()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        
        if(!$id || !in_array($status, ['normal', 'hidden'])){
            $this->error('参数错误');
        }
        
        // 验证是否是自己的服务
        $exists = Db::name('service_teacher')
            ->where('id', $id)
            ->where('teacher_id', $this->auth->id)
            ->find();
            
        if(!$exists){
            $this->error('服务不存在');
        }
        
        // 更新状态
        $result = Db::name('service_teacher')
            ->where('id', $id)
            ->update([
                'status' => $status,
                'updatetime' => time()
            ]);
            
        if($result){
            $this->success('更新成功');
        }else{
            $this->error('更新失败');
        }
    }

    /**
     * 申请提现
     * 
     * @ApiTitle    (申请提现)
     * @ApiMethod   (POST)
     * @ApiParams   (name="money", type="number", required=true, description="提现金额")
     * @ApiParams   (name="type", type="string", required=true, description="提现方式:wechat=微信,alipay=支付宝")
     * @ApiParams   (name="account", type="string", required=false, description="收款账号(支付宝必填)")
     * @ApiParams   (name="real_name", type="string", required=true, description="真实姓名")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": null
      })
     */
    public function withdraw()
    {
        $params = $this->request->post();
        
        // 验证参数
        if(!in_array($params['type'], ['wechat', 'alipay'])){
            $this->error('提现方式错误');
        }
        
        // 验证微信提现时是否绑定openid
        if($params['type'] == 'wechat') {
            if(empty($this->auth->openid)){
                $this->error('请先绑定微信账号');
            }
            $account = $this->auth->openid;
        } else {
            if(empty($params['account'])){
                $this->error('请输入支付宝账号');
            }
            $account = $params['account'];
        }
        $min_price = config('site.min_price');
        $max_price = config('site.max_price');
        $money = floatval($params['money']);
        if($money < $min_price){
            $this->error('提现金额不能小于'.$min_price.'元');
        }
        if($money >= $max_price){
            $this->error('提现金额不能大于'.$max_price.'元');
        }
        if($money < 1){
            $this->error('提现金额必须大于1元');
        }
        
        // 验证余额
        $user = \app\common\model\User::get($this->auth->id);
        if($user->money < $money){
            $this->error('余额不足');
        }
        
        Db::startTrans();
        try {
            // 扣除余额
            $user->setDec('money', $money);
            
            // 添加余额变动记录
            Db::name('user_money_log')->insert([
                'user_id' => $this->auth->id,
                'money' => -$money,
                'before' => $user->money + $money,
                'after' => $user->money,
                'memo' => '提现申请',
                'createtime' => time()
            ]);
            $out_biz_no = 'YQ'.$this->auth->id.date('YmdHis').rand(1000,9999);
            // 创建提现记录
            \app\common\model\Withdraw::create([
                'user_id' => $this->auth->id,
                'money' => $money,
                'out_biz_no' => $out_biz_no,
                'type' => $params['type'],
                'account' => $account,
                'real_name' => $params['real_name'],
                'status' => 'created',
                'createtime' => time()
            ]);
            if($params['type'] == 'wechat') {
                $result = WithdrawService::wechat(
                    $user->openid,  // 使用用户的openid
                    $out_biz_no,
                    $money,
                    $params['real_name'],
                    '提现打款'
                );
            } else {
                $result = WithdrawService::alipay(
                    $account,
                    $out_biz_no,
                    $money,
                    $params['real_name'],
                    '提现打款'
                );
            }
            if($result['status']){
                \app\common\model\Withdraw::where('out_biz_no', $out_biz_no)
                    ->update([
                        'package_info' => $result['package_info'],
                        'status' => 'completed',
                        'updatetime' => time(),
                        'payment_no' => $result['payment_no']
                    ]);
                Db::commit();
                $this->success('申请成功',$result['package_info']);
            }else{
                Db::rollback();
                $this->error('申请失败'.$result['msg']);
            }
            
            
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 提现记录
     * 
     * @ApiTitle    (提现记录)
     * @ApiMethod   (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default="1")
     * @ApiParams   (name="pageSize", type="integer", required=false, description="每页数量", default="10") 
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": "总记录数",
          "per_page": "每页数量", 
          "current_page": "当前页码",
          "last_page": "最后页码",
          "data": [{
            "id": "记录ID",
            "money": "提现金额",
            "type": "提现方式",
            "account": "收款账号",
            "real_name": "真实姓名",
            "status": "状态:created=待审核,approved=已通过,rejected=已驳回,completed=已打款,wait_user_confirm=用户确认中,processing=转账处理中",
            "reason": "驳回原因",
            "createtime": "申请时间",
            "updatetime": "更新时间",
            "package_info": "转账信息",
          }]
        }
      })
     */
    public function withdrawLogs()
    {
        $page = $this->request->get('page', 1);
        $pageSize = $this->request->get('pageSize', 10);
        
        $query = Db::name('withdraw')
            ->where('user_id', $this->auth->id)
            ->order('id DESC');
            
        $total = $query->count();
        $list = $query->page($page, $pageSize)->select();
        
        // 格式化时间
        foreach($list as &$item){
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
            $item['updatetime'] = $item['updatetime'] ? date('Y-m-d H:i:s', $item['updatetime']) : null;
        }
        
        $this->success('', [
            'total' => $total,
            'per_page' => $pageSize,
            'current_page' => $page,
            'last_page' => ceil($total / $pageSize),
            'data' => $list
        ]);
    }
    
    /**
     * 取消订单
     * 
     * @ApiTitle    (取消服务订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "取消成功",
        "data": null
      })
     */
    public function cancelOrder()
    {
        $id = $this->request->post('id');
        
        $order = Db::name('service_order')->where([
            'id' => $id,
            'teacher_id' => $this->auth->id,
            'status' => 0  // 只能取消未支付的订单
        ])->find();

        if (!$order) {
            $this->error('订单不存在或无法取消');
        }

        Db::startTrans();
        try {
            // 更新订单状态为已取消
            $result = Db::name('service_order')->where('id', $id)->update([
                'status' => 3,
                'updatetime' => time()
            ]);
            
            if (!$result) {
                throw new \Exception('取消订单失败');
            }
            
            // 创建系统消息
            \app\common\model\SystemMessage::create([
                'user_id' => $order['user_id'],
                'type' => 'service',
                'title' => '订单已取消',
                'content' => "您的服务订单 {$order['order_no']} 已被老师取消",
                'order_id' => $order['id'],
                'order_no' => $order['order_no']
            ]);

            Db::commit();
            $this->success('取消成功');
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('取消订单失败：' . $e->getMessage());
        }
    }
    
    /**
     * 订单详情
     * 
     * @ApiTitle    (订单详情)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": "订单ID",
          "order_no": "订单编号",
          "service_name": "服务名称",
          "service_icon": "服务图标",
          "service_cover": "服务封面",
          "service_description": "服务描述",
          "user_nickname": "客户昵称",
          "user_avatar": "客户头像",
          "amount": "订单金额",
          "status": "订单状态:0=待支付,1=已支付,2=已完成,3=已取消",
          "pay_type": "支付方式:wechat=微信支付,alipay=支付宝支付,voucher=代金券支付",
          "pay_time": "支付时间",
          "complete_time": "完成时间",
          "createtime": "创建时间"
        }
      })
     */
    public function orderDetail($id)
    {
        $order = Db::name('service_order')->alias('o')
            ->join('service s', 's.id = o.service_id')
            ->join('user u', 'u.id = o.user_id')
            ->where('o.id', $id)
            ->where('o.teacher_id', $this->auth->id)
            ->field([
                'o.*',
                's.name as service_name',
                's.icon as service_icon',
                's.cover_image as service_cover',
                's.description as service_description',
                'u.nickname as user_nickname',
                'u.avatar as user_avatar'
            ])
            ->find();
            
        if(!$order){
            $this->error('订单不存在');
        }
        if ($order['status'] == 0) {
            $order['pay_end_time'] = $order['createtime'] + 7200; // 创建时间加2小时
        }
        // 处理图片完整路径
        $order['service_icon'] = cdnurl($order['service_icon']);
        $order['service_cover'] = cdnurl($order['service_cover']);
        $order['user_avatar'] = cdnurl($order['user_avatar']);
        $order['createtime'] = date('Y-m-d H:i:s', $order['createtime']);
        if($order['pay_time']){
            $order['pay_time'] = date('Y-m-d H:i:s', $order['pay_time']);
        }
        if($order['complete_time']){
            $order['complete_time'] = date('Y-m-d H:i:s', $order['complete_time']);
        }
        
        $this->success('', $order);
    }
}